<template>
  <div
    :class="['vc-component', currNode.currStyle?.['scroll-bar'] ? '' : 'no-scroll-bar']"
    @mouseover.stop="() => mouseoverNode(currNode)"
    @mouseout.stop="() => mouseoverNode(null)"
    @click.stop="activeNode(currNode)"
    :style="style"
  >
    <Component
      v-if="compName"
      ref="compRef"
      :is="compName"
      :node="currNode"
      :inputParam="visual.getInputParam(props.node, props.inputParam)"
      :compStyle="currNode.currCompStyle"
      :compData="currNode.compData"
      :compEvent="currNode.compEvent"
      @mouseoverNode="mouseoverNode"
      @activeNode="activeNode"
      @deleteNode="deleteNode"
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useAdminVisualCompStore } from '@/admin/visual/js/visual-comp';
import visual from "@/visual/js/visual";
import tool from "@/utils/tool";

const emit = defineEmits(['activeNode', 'deleteNode', 'mouseoverNode']);
const props = defineProps({
  node: Object,
  inputParam: Object
});
const visualComp = useAdminVisualCompStore();
const currNode = ref(props.node);

const compRef = ref();
const comp = ref();
const compName = ref('');
const style = ref('');

const activeNode = (node) => {
  emit('activeNode', node);
};

const deleteNode = (item) => {
  emit('deleteNode', item);
};

const mouseoverNode = (item) => {
  emit('mouseoverNode', item)
};

const init = async(node) => {
  currNode.value = node;
  if (!currNode.value.currStyle
      && currNode.value.styleList
      && currNode.value.styleList.length > 0) {
    currNode.value.currStyle = currNode.value.styleList[0].style || {};
  }

  if (!currNode.value.currCompStyle
      && currNode.value.styleList
      && currNode.value.styleList.length > 0) {
    currNode.value.currCompStyle = currNode.value.styleList[0].compStyle || {};
  }

  if (currNode.value.type) {
    comp.value = await visualComp.getVisualComp(currNode.value.type);
    compName.value = comp.value.name;
  }
};

watch(() => tool.deepClone(currNode.value.currStyle), (value) => {
  style.value = visual.parseStyle(value);
}, {immediate: true, deep: true});

watch(() => props.node, () => {
  init(props.node);
}, {deep: true});

onMounted(async() => {
  await init(props.node);
});
</script>

<style scoped lang="scss">
.vc-component > :deep(*) {
  pointer-events: none;
}
.vc-component:has(.vc-component) > * {
  pointer-events: auto;
}
.vc-component:has(.draggable-node) > * {
  pointer-events: auto;
}
.vc-component:has(.empty) {
  width: inherit;
}
.vc-component:has(>.vc-container.empty) {
  width: 100%;
}
.no-scroll-bar::-webkit-scrollbar {
  display: none;
}
</style>